package com.hyjx.framework.component.interfaceservice;

import com.hyjx.framework.common.CommonUtil;
import com.hyjx.framework.common.util.MD5Helper;
import com.hyjx.framework.common.util.StringHelper;
import com.hyjx.framework.component.interfaceservice.dataservice.DataServiceModel;
import com.hyjx.framework.component.interfaceservice.dataservice.SrvConditionModel;
import com.hyjx.framework.component.interfaceservice.datauser.DataUserModel;
import com.hyjx.framework.orm.BaseService;
import com.hyjx.framework.orm.dao.Pager;
import com.hyjx.framework.uc.menu.MenuService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 接口控制器
 */
@Controller
@RequestMapping("/iservice")
public class InterfaceController {
	@Resource
	MenuService menuService;
	@Resource
	BaseService baseService;

	@Resource
	private InterfaceService service;
	private int selectsrv;

	/**
	 * 查询
	 * @param request
	 * @param m
	 * @return
	 */
	@RequestMapping(value = "/g1", produces = "application/json; charset=utf-8")
	@ResponseBody
	public String queryList1(HttpServletRequest request, ConditionModel m) {
		DataServiceModel dataservicemodel = service.findDataService(m.getSrvid());

		List resultJson = service.queryPager(dataservicemodel.getQuerysql(), m.getPageNo(), m.getPageSize());
		JSONArray finJson = JSONArray.fromObject(resultJson);
		return finJson.toString();

	}
	
	
	
	
	
	public void addInterfaceLog(HttpServletRequest request, ConditionModel m,String ip,int amount,String result,String error_msg) {
		InterfaceLogModel im=new InterfaceLogModel();
		 
		im.setIp(ip);
		im.setSrvid(m.getSrvid());
		im.setUserid(m.getUserid());
		im.setPageNo(m.getPageNo());
		im.setPageSize(m.getPageSize());
		im.setTime(new Date());
		im.setCheckBit(m.getCheckBit());
		im.setId(StringHelper.getPrimaryKey());
		im.setAmount(amount);
		im.setResult(result);
		im.setError_msg(error_msg);
		String srv_parameter="";	
		if(selectsrv==1){
			
			List listsrvcondition = service.queryDataConditionService(m.getSrvid());

			for (int i = 0; i < listsrvcondition.size(); i++){
				SrvConditionModel tempmodel = (SrvConditionModel) listsrvcondition.get(i);
				
				String temp = null;
				String getorpost = request.getMethod();
				if (getorpost.equals("GET")) {
					String temp1 = null;
					String temp2 = null;
					String temp3 = null;
					temp1 = request.getParameter(tempmodel.getParameter());
					if(temp1!=null){
						try {
							temp2 = new String(temp1.getBytes("ISO8859-1"));
							temp3 = new String(temp1.getBytes("ISO8859-1"), "UTF-8");
							temp = temp3;
						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					

				} else {
					temp = request.getParameter(tempmodel.getParameter());
				}
				
				if(temp!=null){
					srv_parameter+=tempmodel.getParameter()+"="+temp+" ";
				}else{
					srv_parameter+=tempmodel.getParameter()+"="+"null"+" ";
				}
				//srv_parameter+=tempmodel.getParameter()+"="+temp+" ";
				
			}
			im.setSrv_parameter(srv_parameter);
			String srvtype="select";
			im.setSrvtype(srvtype);
			//插入数据库
			boolean con=service.srvRequestLog(im);
		}else if(selectsrv==2||selectsrv==3){
			//从数据库中得到插入的参数信息
			List listsrvcondition = service.queryDataConditionService(m.getSrvid());
			//解析传如的datajson
			JSONArray arrayobj=JSONArray.fromObject(m.getDatajson());
			
			for(int i=0;i<arrayobj.size();i++){
				JSONObject obj=(JSONObject) arrayobj.get(i);
				for(int j=0;j<listsrvcondition.size();j++){
					SrvConditionModel tempmodel = (SrvConditionModel) listsrvcondition.get(j);
					String para=tempmodel.getParameter();
					String paradata=(String) obj.get(para);
					srv_parameter+=para+"="+paradata+" ";
				}
				String a="& ";
				if(i<arrayobj.size()-1){
					srv_parameter+=a;
				}
				
			}
			im.setSrv_parameter(srv_parameter);
			if(selectsrv==2){
				String srvtype="insert";
				im.setSrvtype(srvtype);
			}else if(selectsrv==3){
				String srvtype="update";
				im.setSrvtype(srvtype);
			}
			
			//插入数据库
			boolean con=service.srvRequestLog(im);
		}
		
		
	}
	
	
	public String getFinSqlBefore(String tempsql1,String datajson){
		String tempsql= tempsql1;
		if(datajson!=null && !datajson.equals("")){
			Map map = (Map)JSONObject.toBean(JSONObject.fromObject(datajson), HashMap.class);
			Set set = map.entrySet();   
			Iterator i = set.iterator(); 
			int start=0;
			while(i.hasNext()){      
			     Map.Entry<String, String> entry1=(Map.Entry<String, String>)i.next();   
			     String key=entry1.getKey();
			     String value=entry1.getValue();
			 	//判断是int还是String ,Int型（int）标识
			     int flag=key.indexOf("(int)");
			     boolean fl=false;
			     if(flag!=-1){
			    	 fl=true;
			    	 key=key.substring(0, flag);
			     }
			     
			   //  System.out.println(entry1.getKey()+"=="+entry1.getValue()); 
			     int index=tempsql.indexOf(key);
			     if(index!=-1){
			    
			    	start=tempsql.lastIndexOf("##", index); 
			    	String stconditionlabel=tempsql.substring(start, start+2);
					tempsql=tempsql.substring(0, start)+tempsql.substring(start+2,tempsql.length());
					 
					 
					int a=tempsql.indexOf(key);
					int b=tempsql.indexOf("##", a);
					 
					String lastconditionlabel=tempsql.substring(b, b+4);
					tempsql=tempsql.substring(0, b)+tempsql.substring(b+4,tempsql.length());
					
					if(fl){
						tempsql=tempsql.replaceAll("#"+key+"#", value);
					}else{
						//tempsql=tempsql.replaceAll("#"+key+"#", "'"+value+"'");
						tempsql=tempsql.replaceAll("#"+key+"#", value);
					}
					
			     }
			     
			} 
		}
		
		return tempsql;
	}
	
	
	
	public String getFinSql(ConditionModel m,HttpServletRequest request,String tempsql,String paratemp){
		List listsrvcondition = service.queryDataConditionService(m.getSrvid());
		//int start=tempsql.indexOf("<c>");
		int start=0;
		Map map=null;
		if(paratemp!=null){
			 map = (Map)JSONObject.toBean(JSONObject.fromObject(paratemp), HashMap.class);
		}else{
			// map = (Map)JSONObject.toBean(JSONObject.fromObject(""), HashMap.class);
		}
		for (int i = 0; i < listsrvcondition.size(); i++) {
			SrvConditionModel tempmodel = (SrvConditionModel) listsrvcondition.get(i);
			String flag=(String) map.get(tempmodel.getParameter());
			if(flag!=null){
				continue;
			}
			
			// 用户传来的参数的值
			String temp = null;
			String getorpost = request.getMethod();

			if (getorpost.equals("GET")) {
				String temp1 = null;
				String temp2 = null;
				String temp3 = null;
				temp1 = request.getParameter(tempmodel.getParameter());
				try {
					temp2 = new String(temp1.getBytes("ISO8859-1"));
					temp3 = new String(temp1.getBytes("ISO8859-1"), "UTF-8");
					temp = temp3;
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			} else {
				temp = request.getParameter(tempmodel.getParameter());
			}
			
			
			if (temp != null&&!temp.equals("")) {
				if (tempmodel.getType().equals("1") ) {
					String para=tempmodel.getParameter();
					int index=tempsql.indexOf(para);
					start=tempsql.lastIndexOf("##", index);
					//找到前面的标签替换为空
					//int c1=tempsql.indexOf(">", start);
					String stconditionlabel=tempsql.substring(start, start+2);
					tempsql=tempsql.substring(0, start)+tempsql.substring(start+2,tempsql.length());
				//	tempsql=tempsql.replaceAll(stconditionlabel, "");
					
					
					//找到后面的标签替换为空
					int a=tempsql.indexOf(para);
					int b=tempsql.indexOf("##", a);
					//int c=tempsql.indexOf(">", b);
					
//					String lastconditionlabel=tempsql.substring(b, b+4);
				//	tempsql=tempsql.replaceAll(lastconditionlabel, "");
					tempsql=tempsql.substring(0, b)+tempsql.substring(b+2,tempsql.length());

					tempsql=tempsql.replaceAll("#"+para+"#",temp);
				//	tempsql=tempsql.replaceAll("#"+para+"#", "'"+temp+"'");
				//	int a11=tempsql.indexOf("'"+temp+"'");
				//	int b11=tempsql.indexOf("<c>", a11);
					
					
					//start=b11;
				} else {
					String para=tempmodel.getParameter();
					int index=tempsql.indexOf(para);
					start=tempsql.lastIndexOf("##", index);
					//找到前面的标签替换为空
					//int c1=tempsql.indexOf(">", start);
					String stconditionlabel=tempsql.substring(start, start+2);
					//tempsql=tempsql.replaceAll(stconditionlabel, "");
					tempsql=tempsql.substring(0, start)+tempsql.substring(start+2,tempsql.length());

					
					//找到后面的标签替换为空
					int a=tempsql.indexOf(para);
					int b=tempsql.indexOf("##", a);
					//int c=tempsql.indexOf(">", b);
					
					
//					String lastconditionlabel=tempsql.substring(b, b+4);
				//	tempsql=tempsql.replaceAll(lastconditionlabel, "");
					tempsql=tempsql.substring(0, b)+tempsql.substring(b+4,tempsql.length());

					tempsql=tempsql.replaceAll("#"+para+"#", temp);
				//	int a11=tempsql.indexOf("'"+temp+"'");
				//	int b11=tempsql.indexOf("<c>", a11);
					
					//start=b11;
				}
			} else {
				// 必传参数为空
				if (tempmodel.getRequired().equals("1")) {
					return null;
				}else{

					String para=tempmodel.getParameter();
					int index=tempsql.indexOf(para);
					start=tempsql.lastIndexOf("##", index);
					//找到前面的标签替换为空
					int a=tempsql.indexOf(para);
					int c=tempsql.indexOf("##", a);
					String str=tempsql.substring(start, c+2);
					
					
					//tempsql=tempsql.replaceAll(str, "");
					tempsql=tempsql.substring(0, start)+tempsql.substring(c+2,tempsql.length());

					
					//start=tempsql.indexOf("<", c11);
					
				}
			}
			
			
			
		}
		return tempsql;
	}
	
	
	
	
	
	public String getFinSql1(ConditionModel m,HttpServletRequest request,String tempsql){
		List listsrvcondition = service.queryDataConditionService(m.getSrvid());
		int start=tempsql.indexOf("<");
		
		for (int i = 0; i < listsrvcondition.size(); i++) {
			SrvConditionModel tempmodel = (SrvConditionModel) listsrvcondition.get(i);
			// 用户传来的参数的值
			String temp = null;
			String getorpost = request.getMethod();

			if (getorpost.equals("GET")) {
				String temp1 = null;
				String temp2 = null;
				String temp3 = null;
				temp1 = request.getParameter(tempmodel.getParameter());
				try {
					temp2 = new String(temp1.getBytes("ISO8859-1"));
					temp3 = new String(temp1.getBytes("ISO8859-1"), "UTF-8");
					temp = temp3;
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			} else {
				temp = request.getParameter(tempmodel.getParameter());
			}
			
			
			if (temp != null&&!temp.equals("")) {
				if (tempmodel.getType().equals("1") ) {
					String para=tempmodel.getParameter();
					
					//找到前面的标签替换为空
					int c1=tempsql.indexOf(">", start);
					String stconditionlabel=tempsql.substring(start, c1+1);
					tempsql=tempsql.replaceAll(stconditionlabel, "");
					
					
					//找到后面的标签替换为空
					int a=tempsql.indexOf(para);
					int b=tempsql.indexOf("</", a);
					int c=tempsql.indexOf(">", b);
					
					String lastconditionlabel=tempsql.substring(b, c+1);
					tempsql=tempsql.replaceAll(lastconditionlabel, "");
					
					tempsql=tempsql.replaceAll("#"+para+"#",temp);
				//	tempsql=tempsql.replaceAll("#"+para+"#", "'"+temp+"'");
					int a11=tempsql.indexOf("'"+temp+"'");
					int b11=tempsql.indexOf("<", a11);
					
					
					start=b11;
				} else {
					String para=tempmodel.getParameter();
					
					//找到前面的标签替换为空
					int c1=tempsql.indexOf(">", start);
					String stconditionlabel=tempsql.substring(start, c1+1);
					tempsql=tempsql.replaceAll(stconditionlabel, "");
					
					
					//找到后面的标签替换为空
					int a=tempsql.indexOf(para);
					int b=tempsql.indexOf("</", a);
					int c=tempsql.indexOf(">", b);
					
					
					String lastconditionlabel=tempsql.substring(b, c+1);
					tempsql=tempsql.replaceAll(lastconditionlabel, "");
					tempsql=tempsql.replaceAll("#"+para+"#", temp);
					int a11=tempsql.indexOf("'"+temp+"'");
					int b11=tempsql.indexOf("</", a11);
					
					start=b11;
				}
			} else {
				// 必传参数为空
				if (tempmodel.getRequired().equals("1")) {
					return null;
				}else{

					String para=tempmodel.getParameter();
					
					//找到前面的标签替换为空
					int a=tempsql.indexOf(para);
					int c=tempsql.indexOf(">", a);
					String str=tempsql.substring(start, c+1);
					
					
					tempsql=tempsql.replaceAll(str, "");
					
					
					//start=tempsql.indexOf("<", c11);
					
				}
			}
			
			
			
		}
		return tempsql;
	}
	
	
	
	//拼接sql的方法
	public String conParameter(ConditionModel m,HttpServletRequest request){
		// 查库，找出srvid服务传入的参数
		List listsrvcondition = service.queryDataConditionService(m.getSrvid());

		/*// 将数据库中相应服务所需的参数找出来
		//List<String> conditionParameter = new ArrayList<String>();
		// 参数对应数据库中的字段内容
		List<String> field_content = new ArrayList<String>();

		// 记录用户传来的条件参数
		List<String> conditionParameterres = new ArrayList<String>();*/

		// 拼接sql条件
		String conditionsql = "";
		for (int i = 0; i < listsrvcondition.size(); i++) {
			SrvConditionModel tempmodel = (SrvConditionModel) listsrvcondition.get(i);
			// 用户传来的参数的值
			String temp=null;
			String getorpost=request.getMethod();
			
			if(getorpost.equals("GET")){
				String temp1=null;
				String temp2=null;
				String temp3=null;
				temp1 = request.getParameter(tempmodel.getParameter());
				try {
					temp2=new String(temp1.getBytes("ISO8859-1"));
					temp3=new String(temp1.getBytes("ISO8859-1"),"UTF-8");
					temp=temp3;
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}else{
				 temp = request.getParameter(tempmodel.getParameter());
			}
						/*try {
				
				//temp = new String(request.getParameter(tempmodel.getParameter()).getBytes("ISO8859-1"),"UTF-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}*/

			//String temp = request.getParameter(tempmodel.getParameter());
			// 如果用户传来的参数不为空
			if (temp != null&&!temp.equals("")) {
				if (tempmodel.getType() == "0") {
					// 类型为int型
					conditionsql = conditionsql + "and ";
					conditionsql = conditionsql + tempmodel.getField_content() + "=" + temp;
				} else {
					conditionsql = conditionsql + "and ";
					conditionsql = conditionsql + tempmodel.getField_content() + "=" + "'" + temp + "'";
				}
			} else {
				// 必传参数为空
				if (tempmodel.getRequired() == "1") {
					return null;
				}
			}
			
		}
		// 去掉最后的and
		/*int end = conditionsql.length() - 4;
		conditionsql = conditionsql.substring(0, end);*/

		return conditionsql;
	}
	
	public String returnErrorJson(String result,String error_msg,int total,ConditionModel m){
		 StringBuffer sb = new StringBuffer();
		    sb.append("{");
			sb.append("\"result\": "+result+",");
			sb.append("\"error_msg\": \""+error_msg+"\",");
			sb.append("\"data\": ");
			sb.append("{");
			sb.append("\"total\": "+total+",");
			sb.append("\"pageNo\": "+m.getPageNo()+",");
			sb.append("\"pageSize\": "+m.getPageSize()+",");
			sb.append("\"rows\": ");
			sb.append("\"没有数据\"");
			sb.append("}");
			sb.append("}");
			String f1=sb.toString();
			return f1;
	}

	/**
	 * 执行客户查询操作
	 * @RequestMapping(value = "/g", produces = "application/json; charset=utf-8")
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/g",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String queryList(HttpServletRequest request) {
		selectsrv=1;
		int amount=0;
		String param="";
		String result="";
		String error_msg="";
		String ip="";
		java.sql.Connection con = null;
		JSONObject finJson = null;
		ConditionModel m=new ConditionModel();
		try {
			request.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e2) {
			e2.printStackTrace();
		}
		
	    try {	
			 m.setUserlogname(request.getParameter("userlogname"));
			 m.setSrvid(request.getParameter("srvid"));
			 m.setCheckBit(request.getParameter("checkBit"));
			 m.setDesc(request.getParameter("desc"));
			 m.setPageNo(request.getParameter("pageNo"));
			 m.setPageSize(request.getParameter("pageSize"));
			 m.setTimeStamp(request.getParameter("timeStamp"));
			 m.setSqlcondition(request.getParameter("sqlcondition"));
			//根据用户登录名找出用户id
			 String userid=service.queryUserIdByLogName(m.getUserlogname());
			 m.setUserid(userid);
			 ip = request.getHeader("X-Forwarded-For"); 
				if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
					 ip = request.getHeader("Proxy-Client-IP"); 
				}
				if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
					 ip = request.getHeader("WL-Proxy-Client-IP"); 
				}
				if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
					 ip = request.getHeader("HTTP_CLIENT_IP"); 
				}
				if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
					ip = request.getHeader("HTTP_X_FORWARDED_FOR");
				}
				 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
					 ip = request.getRemoteAddr(); 
				 }			 
			 if(m.getPageSize()==null||"".equals(m.getPageSize())||m.getUserlogname()==null||m.getSrvid()==null||m.getTimeStamp()==null||m.getCheckBit()==null){
				 result="0";
				 error_msg="参数不正确";
				 return returnErrorJson(result, error_msg, 0,m);
			 }
			if(Integer.parseInt(m.getPageSize())>50){
				 result="0";
				 error_msg="超过每页最大限定数量50";
				 return returnErrorJson(result, error_msg, 0,m);
			}
			 //增加请求的日志记录
			// 将取出来来的userinfo和dataservice信息放入SysConstants类里面缓存，然后判断传入的userid和srvid是否存在
			// 这里有问题（已解决，刷新缓存）
			Map<String, DataUserModel> userinfo = InterFaceConstants.getUserConfig();
			Map<String, DataServiceModel> serviceinfo = InterFaceConstants.getServiceConfig();
			DataUserModel usermodelinfo = userinfo.get(m.getUserid());
			if (usermodelinfo == null) {
			    result="0";
			    error_msg="用户不存在！";
				return returnErrorJson(result, error_msg, 0,m);
				}
			String para=usermodelinfo.getParameter();
			DataServiceModel servicemodelinfo = serviceinfo.get(m.getSrvid());
			//得到服务类型，判断是否是查询服务
			String srvtype=servicemodelinfo.getSrvtype();		
			// 根据传入的时间戳判断请求是否过期
			boolean time = false;
			String timeStamp = m.getTimeStamp();
			Date date = new Date();
			DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
			String currenttime = format.format(date);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			Date date2 = null;
			try {
				date2 = sdf.parse(timeStamp);
			} catch (ParseException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			long timediff = 0;
			long timeDelta = (date.getTime() - date2.getTime()) / 1000;
			timediff = timeDelta > 0 ? (long) timeDelta : (long) Math.abs(timeDelta);	
			if (timediff <= 1200) {
				time = false;
			} else {
				time = true;
			}
			//得到用户和服务是否有效的信息
			String uservalidity=usermodelinfo.getValidity();
			String servicevalidity=servicemodelinfo.getValidity();
			//得到服务所需的数据源
			String datasource=servicemodelinfo.getDatasource();			
			//得到用户的ip范围
			boolean iplimit=true;
			String iprange=usermodelinfo.getRestrictedips();
			if(iprange==null||iprange.equals("")){
				iplimit=false;
			}else{
				iplimit=!ip.matches(iprange);
			}						
			// 判断传入的userid和srvid是否在数据库里面存在，如果不存在废弃掉改请求
			if (servicemodelinfo == null) {
			    result="0";
			    error_msg="服务不存在！";
				return returnErrorJson(result, error_msg, 0,m);
			}else if(uservalidity.equals("0")||servicevalidity.equals("0")){
				//判断如果用户或者服务无效的情况
				result="0";
			    error_msg="用户或者服务无效！";
			    return returnErrorJson(result, error_msg, 0,m);
			}else if(!srvtype.equals("01")){
				//判断是否是查询服务
				result="0";
			    error_msg="该服务不是查询服务！";
			    return returnErrorJson(result, error_msg, 0,m);
			} else {
				// 时间戳来判断请求是否过期
				if (time) {
					result="0";
				    error_msg="时间戳超时！";
					return returnErrorJson(result, error_msg, 0,m);
				} else if (m.getDesc() != null) {
					if (m.getDesc().equals("1")) {
						String querySqlDesc = service.findSqlDesc(m.getSrvid());
						// System.out.println(querySqlDesc);
						return querySqlDesc;
					} else {
						// 有待扩展
						result="0";
					    error_msg="服务id错误！";
						return returnErrorJson(result, error_msg, 0,m);
					}
				} else if(iplimit){
						//判断用户ip范围是否符合
				        result="0";
				        error_msg="ip范围限制";
				        return returnErrorJson(result, error_msg, 0,m);
					} else {				
					// 拼接get请求传来的参数
					String connectparameter = m.getUserlogname() + m.getSrvid() +m.getTimeStamp();

					// 获得srv_userInfo表里的私钥，以便对connectparameter MD5加密
					UserInfoModel userinfomodel = service.findUserInfo(m.getUserid());
					String privatekey = userinfomodel.getPrivatekey();
					// 将私钥拼接到connectparameter
					connectparameter += privatekey;
					String md5string = "";
					// 对connectparameter进行MD5加密
					try {
						md5string = MD5Helper.encrypt(connectparameter);
					} catch (NoSuchAlgorithmException e) {
						e.printStackTrace();
					}
					// 加密后生成的string和请求传入的校验位进行比较
					if (md5string.equals(m.getCheckBit())) {
						// 判断该用户是否有相应的权限,如果有权限提供相应的服务
						String limitadmit = (String) service.limitAdmit(m);
						if (limitadmit != null) {
							DataServiceModel dataservicemodel = service.findDataService(m.getSrvid());
							String sql = dataservicemodel.getQuerysql();
							//生成待执行的sql
							String excuteSql = getExecuteSql(m,request,sql,para);
							
							Pager pager = service.queryPagerAll(excuteSql, m.getPageNo(), m.getPageSize());

							List list = pager.getResultList();
							int total = pager.getEndIndex();
							amount=list.size();
							result="1";
							error_msg="";
							StringBuffer sb = new StringBuffer();								
							if(list.size()>0){
								sb.append("{");
								sb.append("\"result\": "+result+",");
								sb.append("\"error_msg\": \""+error_msg+"\",");
								sb.append("\"data\": ");
								sb.append("{");
								sb.append("\"total\": "+total+",");
								sb.append("\"pageNo\": "+m.getPageNo()+",");
								sb.append("\"pageSize\": "+m.getPageSize()+",");
								sb.append("\"rows\": ");
								sb.append(CommonUtil.getJsonString(list).toString());
								sb.append("}");
								sb.append("}");
							}else{
								sb.append("{");
								sb.append("\"result\": "+result+",");
								sb.append("\"error_msg\": \""+error_msg+"\",");
								sb.append("\"data\": ");
								sb.append("{");
								sb.append("\"total\": "+total+",");
								sb.append("\"pageNo\": "+m.getPageNo()+",");
								sb.append("\"pageSize\": "+m.getPageSize()+",");
								sb.append("\"rows\": ");
								sb.append("\"无对应的数据\"");
								sb.append("}");
								sb.append("}");
							}
							String f1=sb.toString();
							finJson = JSONObject.fromObject(f1);
						}else{
							// 用户没有请求服务的权限
							result="0";
							error_msg="没有权限请求服务";
							return returnErrorJson(result, error_msg, 0,m);
						}
					} else {
						// 用户没有请求服务的权限
						result="0";
						error_msg="校验参数错误";
						return returnErrorJson(result, error_msg, 0,m);
					}
				}
			}
		} catch (Exception e) {
			result="0";
			error_msg="系统级异常："+e.getMessage();
			e.printStackTrace();
			amount=0;
			return returnErrorJson(result, error_msg, 0,m);
		}finally{//记录日志			
			 addInterfaceLog(request,m,ip,amount,result,error_msg);
			 if(con != null){
				 try {
					con.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			 }
		}
	    return finJson.toString();
	}
	
	
	/**
	 * 获得数据库类型  1oracle 2mysql 9未知数据库类型
	 * @param driverClassName
	 * @return
	 */
	public int getDBType(String driverClassName){
		if(driverClassName.indexOf("oracle")!= -1){
			return 1;
		}else if(driverClassName.indexOf("mysql")!= -1){
			return 2;
		}
		return 9;
	}
	
	/***
	 * 将参数的值填充到要执行的sql中
	 * @param m
	 * @param request
	 * @param sql
	 * @return
	 * @throws Exception 
	 */
	public String getExecuteSql(ConditionModel m, HttpServletRequest request, String sql, String userPara) throws Exception{
		/**
		 * 获取本服务需要的所有参数信息
		 */
		List<SrvConditionModel> listsrvcondition = service.queryDataConditionService(m.getSrvid());
		Map<String, String> paraMap = new HashMap<String, String>();
		JSONObject jsonObj=JSONObject.fromObject(userPara);
		for(SrvConditionModel temp : listsrvcondition){
			String para = temp.getParameter();
			String paraValue = request.getParameter(para);
			paraValue=new String(paraValue.getBytes("iso-8859-1"),"utf-8");
			if(paraValue != null && !"".equals(paraValue)){
				paraMap.put(para, paraValue);
			}else if(!jsonObj.isNullObject() && jsonObj.containsKey(para)){
				paraValue = jsonObj.getString(para);
				if(paraValue != null && !"".equals(paraValue)){
					paraMap.put(para, paraValue);
				}
			}
		}
		String headerSql = sql.substring(0, sql.indexOf("##"));
		String endSql = sql.substring(sql.lastIndexOf("##")+2);
		String whereSql = sql.substring(sql.indexOf("##")+2, sql.lastIndexOf("##"));
		String[] paraSqls = whereSql.split("@");
		whereSql = "";
		for(String key:paraMap.keySet()){
			for(String paraSql:paraSqls){
				if(paraSql.indexOf(key)>-1){
					whereSql += " " + paraSql.replaceAll("#"+key+"#", paraMap.get(key));
				}
			}
		}
		return headerSql + whereSql + endSql;
	}
	
	/**
	 * 执行客户数据导入操作
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/i",produces="text/html;charset=UTF-8" )
	@ResponseBody
	public String insertList(HttpServletRequest request, @RequestBody String data){
		selectsrv=2;
		
		ConditionModel m = new ConditionModel();
		m.setUserlogname(request.getParameter("userlogname"));
		m.setSrvid(request.getParameter("srvid"));
	//	m.setUserid(request.getParameter("userid"));
		m.setCheckBit(request.getParameter("checkBit"));
		m.setTimeStamp(request.getParameter("timeStamp"));
		m.setDatajson(request.getParameter("datajson"));
		
		//根据用户登录名找出用户id
		String userid=service.queryUserIdByLogName(m.getUserlogname());
		m.setUserid(userid);
		
		//ip限制
		String ip = request.getHeader("X-Forwarded-For"); 
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
			 ip = request.getHeader("Proxy-Client-IP"); 
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
			 ip = request.getHeader("WL-Proxy-Client-IP"); 
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
			 ip = request.getHeader("HTTP_CLIENT_IP"); 
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
			 ip = request.getRemoteAddr(); 
		 }
		
		 
		 //增加请求的日志记录
		 //addInterfaceLog(request,m,ip);
		
		 //第一，先判断该请求是否过期
		boolean time = false;
		String timeStamp = m.getTimeStamp();
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		Date date2 = null;
		try {
			date2 = sdf.parse(timeStamp);
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		long timediff = 0;
		long timeDelta = (date.getTime() - date2.getTime()) / 1000;
		timediff = timeDelta > 0 ? (long) timeDelta : (long) Math.abs(timeDelta);
		if (timediff <= 1200) {
			time = false;
		} else {
			time = true;
		}
		
		//得到用户和服务的相关信息，判断用户服务是否存在；用户服务是否都有效；服务是否是插入服务等
		Map<String, DataUserModel> userinfo = InterFaceConstants.getUserConfig();
		Map<String, DataServiceModel> serviceinfo = InterFaceConstants.getServiceConfig();

		DataUserModel usermodelinfo = userinfo.get(m.getUserid());
		DataServiceModel servicemodelinfo = serviceinfo.get(m.getSrvid());
		//得到用户和服务是否有效的信息
		String uservalidity = usermodelinfo != null ? usermodelinfo.getValidity() : "";
		String servicevalidity = servicemodelinfo != null ? servicemodelinfo.getValidity() : "";
		//得到服务类型，判断是否是插入服务
		String srvtype = servicemodelinfo != null ? servicemodelinfo.getSrvtype() : "";
		
		
		//得到用户的ip范围
		boolean iplimit = true;
		String iprange = usermodelinfo != null ? usermodelinfo.getRestrictedips() : "";
		if (iprange == null || iprange.equals("")) {
			iplimit = false;
		} else {
			iplimit = !ip.matches(iprange);
		}
		
		
		
		
		
		//判定该请求是否合理
		if(time){
			return"请求超时！";
		}else if(iplimit&&false){
			return"ip限制！";
		}else if(usermodelinfo == null || servicemodelinfo == null){
			return"用户或者服务不存在！";
		}else if(uservalidity.equals("0")||servicevalidity.equals("0")){
			return"用户或者服务无效！";
		}else if(!srvtype.equals("03")){
			return"该服务不是插入服务！";
		}else{
			//md5加密，与校验为比较
			// 拼接get请求传来的参数
			String connectparameter = m.getUserlogname()  + m.getSrvid() +m.getTimeStamp();

			// 获得srv_userInfo表里的私钥，以便对connectparameter MD5加密
			UserInfoModel userinfomodel = service.findUserInfo(m.getUserid());
			String privatekey = userinfomodel.getPrivatekey();

			// 将私钥拼接到connectparameter
			connectparameter += privatekey;
			String md5string = "";
			// 对connectparameter进行MD5加密
			try {

				md5string = MD5Helper.encrypt(connectparameter);
				// md5string1=MD5Helper.encryptTemp(connectparameter,"rre");
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			if(md5string.equals(m.getCheckBit())){
				//从数据库中得到插入服务的sql信息
				DataServiceModel dataservicemodel = service.findDataService(m.getSrvid());
				String sql = dataservicemodel.getQuerysql();
				//从数据库中得到插入的参数信息
				List listsrvcondition = service.queryDataConditionService(m.getSrvid());
				
				//解析传如的datajson
				JSONArray arrayobj=JSONArray.fromObject(m.getDatajson());
				//记录插入出错的数据
				List<String> list=new ArrayList<String>();
				int s=0;
				int f=0;
				for(int i=0;i<arrayobj.size();i++){
					JSONObject obj=(JSONObject) arrayobj.get(i);
					String tempsql=sql;
					for(int j=0;j<listsrvcondition.size();j++){
						SrvConditionModel tempmodel = (SrvConditionModel) listsrvcondition.get(j);
						//判断插入参数的类型
						if(tempmodel.getType().equals("1")){
							String para=tempmodel.getParameter();
							String paradata=(String) obj.get(para);
							//tempsql=tempsql.replaceAll("#"+para+"#", "'"+paradata+"'");
							tempsql=tempsql.replaceAll("#"+para+"#", paradata);
						}else{
							String para=tempmodel.getParameter();
							String paradata=(String) obj.get(para);
							tempsql=tempsql.replaceAll("#"+para+"#", paradata);
						}
						
					}
					
					//执行数据库的插入操作
					boolean con=service.insertData(tempsql);
					if(!con){
						list.add(""+i+" ");
						f++;
					}else{
						s++;
					}
					
					
				}
				if(list.size()==0){
					return "成功了"+s+"条数据";
				}else{
					return "成功了"+s+"条数据"+"第"+list.toString()+"插入出错";
				}
				
				
			}else{
				return"没有服务权限！";
			}
		}
		
		 
	}
	
	
	
	
	
	/**
	 * 执行客户数据导入操作
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/u",produces="text/html;charset=UTF-8" )
	@ResponseBody
	public String upDateList(HttpServletRequest request, @RequestBody String data){
		selectsrv=3;
		
		ConditionModel m = new ConditionModel();
		m.setUserlogname(request.getParameter("userlogname"));
		m.setSrvid(request.getParameter("srvid"));
	//	m.setUserid(request.getParameter("userid"));
		m.setCheckBit(request.getParameter("checkBit"));
		m.setTimeStamp(request.getParameter("timeStamp"));
		m.setDatajson(request.getParameter("datajson"));
		
		//根据用户登录名找出用户id
		String userid=service.queryUserIdByLogName(m.getUserlogname());
		m.setUserid(userid);
		
		//ip限制
		String ip = request.getHeader("X-Forwarded-For"); 
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
			 ip = request.getHeader("Proxy-Client-IP"); 
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
			 ip = request.getHeader("WL-Proxy-Client-IP"); 
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
			 ip = request.getHeader("HTTP_CLIENT_IP"); 
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
			 ip = request.getRemoteAddr(); 
		 }
		
		 //增加请求的日志记录
		// addInterfaceLog(request,m,ip);
		 
		 
		 //第一，先判断该请求是否过期
		boolean time = false;
		String timeStamp = m.getTimeStamp();
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		Date date2 = null;
		try {
			date2 = sdf.parse(timeStamp);
		} catch (ParseException e1) {
			e1.printStackTrace();
		}
		long timediff = 0;
		long timeDelta = (date.getTime() - date2.getTime()) / 1000;
		timediff = timeDelta > 0 ? (long) timeDelta : (long) Math.abs(timeDelta);
		if (timediff <= 1200) {
			time = false;
		} else {
			time = true;
		}
		
		//得到用户和服务的相关信息，判断用户服务是否存在；用户服务是否都有效；服务是否是插入服务等
		Map<String, DataUserModel> userinfo = InterFaceConstants.getUserConfig();
		Map<String, DataServiceModel> serviceinfo = InterFaceConstants.getServiceConfig();

		DataUserModel usermodelinfo = userinfo.get(m.getUserid());
		DataServiceModel servicemodelinfo = serviceinfo.get(m.getSrvid());
		//得到用户和服务是否有效的信息
		String uservalidity=usermodelinfo.getValidity();
		String servicevalidity=servicemodelinfo.getValidity();
		//得到服务类型，判断是否是插入服务
		String srvtype=servicemodelinfo.getSrvtype();
		
		
		//得到用户的ip范围
		boolean iplimit = true;
		String iprange = usermodelinfo.getRestrictedips();
		if (iprange == null || iprange.equals("")) {
			iplimit = false;
		} else {
			iplimit = !ip.matches(iprange);
		}
		
		
		
		
		
		//判定该请求是否合理
		if(time){
			return"请求超时！";
		}else if(iplimit&&false){
			return"ip限制！";
		}else if(usermodelinfo == null || servicemodelinfo == null){
			return"用户或者服务不存在！";
		}else if(uservalidity.equals("0")||servicevalidity.equals("0")){
			return"用户或者服务无效！";
		}else if(!srvtype.equals("02")){
			return"该服务不是插入服务！";
		}else{
			//md5加密，与校验为比较
			// 拼接get请求传来的参数
			String connectparameter = m.getUserlogname() + m.getSrvid() +m.getTimeStamp();

			// 获得srv_userInfo表里的私钥，以便对connectparameter MD5加密
			UserInfoModel userinfomodel = service.findUserInfo(m.getUserid());
			String privatekey = userinfomodel.getPrivatekey();

			// 将私钥拼接到connectparameter
			connectparameter += privatekey;
			String md5string = "";
			// 对connectparameter进行MD5加密
			try {

				md5string = MD5Helper.encrypt(connectparameter);
				// md5string1=MD5Helper.encryptTemp(connectparameter,"rre");
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			if(md5string.equals(m.getCheckBit())){
				//从数据库中得到gengxin服务的sql信息
				DataServiceModel dataservicemodel = service.findDataService(m.getSrvid());
				String sql = dataservicemodel.getQuerysql();
				//从数据库中得到更新的参数信息
				List listsrvcondition = service.queryDataConditionService(m.getSrvid());
				
				//解析传如的datajson
				JSONArray arrayobj=JSONArray.fromObject(m.getDatajson());
				//记录更新出错的数据
				List<String> list=new ArrayList<String>();
				int total=0;
				for(int i=0;i<arrayobj.size();i++){
					JSONObject obj=(JSONObject) arrayobj.get(i);
					String tempsql=sql;
					for(int j=0;j<listsrvcondition.size();j++){
						SrvConditionModel tempmodel = (SrvConditionModel) listsrvcondition.get(j);
						//判断gengxin参数的类型
						if(tempmodel.getType().equals("1")){
							String para=tempmodel.getParameter();
							String paradata=(String) obj.get(para);
							tempsql=tempsql.replaceAll("#"+para+"#", paradata);
							//tempsql=tempsql.replaceAll("#"+para+"#", "'"+paradata+"'");
						}else{
							String para=tempmodel.getParameter();
							String paradata=(String) obj.get(para);
							tempsql=tempsql.replaceAll("#"+para+"#", paradata);
						}
						
					}
					
					//执行数据库的更新操作
					int con=service.updateData(tempsql);
					if(con>0){
						total+=con;
					}else{
						list.add(""+i+" ");
						
					}
					
					
				}
				if(list.size()==0){
					return "更新了"+total+"条数据";
				}else{
					return "更新了"+total+"条数据"+"第"+list.toString()+"更新出错";
				}
				
				
			}else{
				return"没有服务权限！";
			}
		}
		
		 
	}
	
	
	
	
	
	
}